﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>subscribe的使用</title>
    <script src="jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="knockout-2.1.0.js" type="text/javascript"></script>
</head>
<body>
    <p>
        <select data-bind='options: categories, optionsText: "name", optionsCaption: "Select...", optionsValue:"values",value: selectCategory'></select>
        <!-- Appears when you select something -->
        You have chosen a category
    <span data-bind="text: selectCategory"></span>.
    </p>
    <p>
        The name is
        <input type="text" data-bind="value: personName" /><span style="color: red" id="changeName"></span>
        this fullName is <span data-bind="text: fullName"></span>
    </p>
    <p>
        Enter bid price:
        <input data-bind="value: formattedPrice" />
        <span data-bind="text: price" />
    </p>

    

    <script>

        //监控属性
        var myViewModel = function () {
            self = this;
            self.personName = ko.observable('Bob');
            self.personAge = ko.observable(123);
            self.formattedPrice = ko.observable(0);
            self.price = ko.observable(0);
            self.categories = ko.observableArray([{ name: 'one', values: 1 }, { name: 'tow', values: 2 }]);

            self.selectCategory = ko.observable();

            //订阅属性
            self.personName.subscribe(function (a) {
                $("#changeName").html("名称发生变化：" + a);
            });
        }

        var modelObj = new myViewModel();



        //依赖属性
        modelObj.fullName = ko.dependentObservable(function () {
            return this.personName() + this.personAge();
        }, modelObj); //它是声明执行依赖监控属性的this用的。 没有它，你不能引用到this.firstName() 和this.lastName()。 

        //依赖属性
        modelObj.formattedPrice = ko.dependentObservable({

            read: function () {
                return "$" + this.price().toFixed(2);
            },

            write: function (value) {
                // Strip out unwanted characters, parse as float, then write the raw data back to the underlying "price" observable，从字符中拿出数字
                value = parseFloat(value.replace(/[^\.\d]/g, ""));
                this.price(isNaN(value) ? 0 : value); // Write to underlying storage
            },
            owner: modelObj
        });



        //重新赋值
        modelObj.personName("abc").personAge(456);

        ko.applyBindings(modelObj);
    </script>
</body>
</html>
